package com.yantong.controller.product;

import com.yantong.pojo.Category;
import com.yantong.service.CategoryService;
import com.yantong.controller.BaseController;
import com.yantong.result.ResultVo;
import com.yantong.utils.DateUtils;
import com.yantong.utils.PageUtils;
import com.yantong.utils.excel.ExcelHelper;
import com.yantong.service.DispatchService;
import com.yantong.service.ConfigService;
import com.yantong.pojo.Product;
import com.yantong.pojo.ProductCentre;
import com.yantong.enums.PropertiesEnum;
import com.yantong.pojo.vo.ProductCentreVo;
import com.yantong.pojo.vo.ProductVo;
import com.yantong.service.ProductCentreService;
import com.yantong.service.ProductService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 商品
 * 
 * @author baolingyu
 * @date 2018年8月28日
 */
@Controller
@RequestMapping("/product/manage")
public class ProductController extends BaseController{
	private static final String prefix = "product";
	
	private Logger logger = LoggerFactory.getLogger(ProductController.class);

	@Autowired
	private CategoryService categoryService;
	@Autowired
	private ProductService productService;
	@Autowired
	private DispatchService dispatchService;
	@Autowired
	private ProductCentreService pCentreService;
	@Autowired
	private ConfigService configService;

	/**
	 * 跳转页面：所有商户商品页面
	 *
	 * @return
	 */
	@GetMapping()
	@RequiresPermissions("product:manage:manage")
	public String products(Model model) {
		Category category = new Category();
		category.setParentid(0L);
		model.addAttribute("category", categoryService.getListCategory(category));
		model.addAllAttributes(getCentreIdModelInfo());
		return prefix + "/products";
	}
	
	/**
	 * 跳转页面：拼团页面
	 *
	 * @return
	 */
	@GetMapping("/tospellgroupPage")
	@RequiresPermissions("product:manage:spellgroup")
	public String tospellgroupPage(Model model) {
		Category category = new Category();
		category.setParentid(0L);
		model.addAttribute("category", categoryService.getListCategory(category));
		model.addAllAttributes(getCentreIdModelInfo());
		return prefix + "/spellgroup";
	}

	/**
	 * 跳转页面：秒杀页面
	 *
	 * @return
	 */
	@GetMapping("/toSeckillPage")
	@RequiresPermissions("product:manage:seckill")
	public String toSeckillPage(Model model) {
		Category category = new Category();
		category.setParentid(0L);
		model.addAttribute("category", categoryService.getListCategory(category));
		model.addAllAttributes(getCentreIdModelInfo());
		return prefix + "/seckill";
	}

	/**
	 * 跳转页面：预售商品界面
	 *
	 * @return
	 */
	@GetMapping("/toSpresellPage")
	@RequiresPermissions("product:manage:spresell")
	public String toSpresellPage(Model model) {
		Category category = new Category();
		category.setParentid(0L);
		model.addAttribute("category", categoryService.getListCategory(category));
		model.addAllAttributes(getCentreIdModelInfo());
		return prefix + "/spresell";
	}

	/**
	 * 跳转页面：预约商品界面
	 *
	 * @return
	 */
	@GetMapping("/toYuyuePage")
	@RequiresPermissions("product:manage:yuyue")
	public String toYuyuePage(Model model) {
		Category category = new Category();
		category.setParentid(0L);
		model.addAttribute("category", categoryService.getListCategory(category));
		model.addAllAttributes(getCentreIdModelInfo());
		return prefix + "/yuyue";
	}

	/**
	 * 跳转页面：积分商品界面
	 *
	 * @return
	 */
	@GetMapping("/toScorePage")
	@RequiresPermissions("product:manage:score")
	public String toScorePage(Model model) {
		Category category = new Category();
		category.setParentid(0L);
		model.addAttribute("category", categoryService.getListCategory(category));
		model.addAllAttributes(getCentreIdModelInfo());
		return prefix + "/score";
	}
	
	/**
	 * 跳转到商品库列表页面
	 *
	 * @return
	 */
	@GetMapping("/productbases")
	@RequiresPermissions("product:manage:manage")
	public String productbases(Model model) {
		Category category = new Category();
		category.setParentid(0L);
		model.addAttribute("category", categoryService.getListCategory(category));
		return prefix + "/productbases";
	}

	/**
	 * 列表,这里是取商品库商品
	 * 
	 * @return
	 * @author baolingyu
	 * @date 2018年8月28日-上午11:41:11
	 */
	@GetMapping("/list")
	@ResponseBody
	@RequiresPermissions("product:manage:manage")
	public PageUtils<Product> list(int offset, int limit, Product vo) {
		return productService.list(offset, limit, vo);
	}
	
	
	/**
	 * 统计平台商品成本总金额/利润
	 * @param vo
	 * @return
	 */
	@RequiresPermissions("product:manage:manage")
	@PostMapping("/sumcostprice")
	@ResponseBody
	public Object sumcostprice(Product vo) {
		return productService.sumcostprice(vo);
	}
	
	/**
	 * 列表，这里是取所有商户商品
	 * @param offset
	 * @param limit
	 * @param vo
	 * @param centreId
	 * @return
	 * @author baolingyu
	 * @date 2018年11月5日-下午4:22:04
	 */
	@GetMapping("/listAll")
	@ResponseBody
	@RequiresPermissions("product:manage:manage")
	public PageUtils<ProductCentre> listAll(int offset, int limit, ProductCentreVo vo) {
		vo.setAuditing(0);
		if(getUserTeamId() != null){
			vo.setLiansuoid(getUserTeamId());
		}
		return pCentreService.listCentreProducts(offset, limit, vo, "");
	}
	
	
	/**
	 * 跳转新增页面
	 * @param model
	 * @return
	 * @author baolingyu
	 * @date 2018年9月2日-下午12:48:55
	 */
	@RequiresPermissions("product:manage:add")
	@GetMapping("/toAdd")
	public String toAdd(Model model) {
		Category category = new Category();
		category.setParentid(0L);
		Long centreId = getUserCentreId();
		Long teamId = getUserTeamId();
//		boolean bol = getZbFlag();
		model.addAttribute("mallCodeFlag", false);
		model.addAttribute("category", categoryService.getListCategory(category));
		model.addAttribute("dispatch", dispatchService.getDispatchList(null, 0, centreId, teamId));
		return prefix + "/add";
	}

	/**
	 * 新增
	 * 
	 * @param vo
	 * @return
	 * @author baolingyu
	 * @date 2018年8月28日-上午11:41:19
	 */
	@RequiresPermissions("product:manage:add")
	@PostMapping("/save")
	@ResponseBody
	public ResultVo save(@RequestBody ProductVo vo) {
		if (vo == null) {
			return ResultVo.error();
		}
		vo.setCreUnm(getNikeName());
		vo.setUpdUnm(getNikeName());
		vo.setCreDt(new Date());
		vo.setUpdDt(new Date());
		if(vo.getSuggestsaleprice()!=null && vo.getMarketprice()!=null && vo.getSuggestsaleprice().compareTo(vo.getMarketprice())==-1) {
			return ResultVo.error("建议零售价不能小于现价");
		}
		if(vo.getId()==null){
			if (productService.save(vo) < 1) {
				return ResultVo.error();
			}
		}else if (productService.update(vo) < 1) {
			return ResultVo.error();
		}
		return ResultVo.ok(vo.getId()+"");
	}
	
	
	
	/**
	 * 商品详情，带规格+规格属性+sku
	 * @param id
	 * @return
	 * @author baolingyu
	 * @date 2018年9月18日-下午4:06:50
	 */
	@RequiresPermissions("product:manage:edit")
	@GetMapping("/detail")
	@ResponseBody
	public ProductVo detail(Long id) {
		return productService.detail(id);
	}

	/**
	 * 跳转到编辑页面
	 *
	 * @param model
	 * @return
	 * @author baolingyu
	 * @date 2018年8月28日-下午2:12:57
	 */
	@RequiresPermissions("product:manage:edit")
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable Long id, Model model) {
		Category category = new Category();
		category.setParentid(0L);

//		boolean bol = getZbFlag();
		Long centreId = getUserCentreId();
		Long teamId = getUserTeamId();
		model.addAttribute("mallCodeFlag", false);

		model.addAttribute("product", productService.getByKey(id));
		model.addAttribute("dispatch", dispatchService.getDispatchList(null, 0, centreId, teamId));
		model.addAttribute("category", categoryService.getListCategory(category));
		return prefix + "/edit";
	}

	/**
	 * 更新
	 * 
	 * @param vo
	 * @return
	 * @author baolingyu
	 * @date 2018年8月28日-下午2:13:49
	 */
	@RequiresPermissions("product:manage:edit")
	@PostMapping("/update")
	@ResponseBody
	public ResultVo update(@RequestBody ProductVo vo) {
		if (vo == null) {
			return ResultVo.error();
		}
		vo.setUpdUnm(getNikeName());
		vo.setUpdDt(new Date());
		

		if (productService.update(vo) < 1) {
			return ResultVo.error();
		}
		return ResultVo.ok();
	}

	/**
	 * 商品列表点击button，更新商品
	 * @return
	 * @author baolingyu
	 * @date 2018年10月8日-下午9:36:40
	 */
	@RequiresPermissions("product:manage:edit")
	@PostMapping("/btnUpdate")
	@ResponseBody
	public ResultVo btnUpdate(Long id, String column) {
		if (id == 0 || id == null) {
			return ResultVo.error();
		}
		if (productService.btnUpdate(id, column) < 1) {
			return ResultVo.error();
		}
		return ResultVo.ok();
	}

	/**
	 * 更新库存
	 * @param id
	 * @param total
	 * @return
	 * @author baolingyu
	 * @date 2018年10月15日-下午2:13:47
	 */
	@RequiresPermissions("product:manage:edit")
	@PostMapping("/updateTotal")
	@ResponseBody
	public ResultVo updateTotal(Long id, int total) {
		if (id == 0 || id == null) {
			return ResultVo.error();
		}

		try {
			if (productService.updateTotal(id, total) < 1) {
				return ResultVo.error();
			}
		} catch (Exception e) {
			return ResultVo.error(e.getMessage());
		}
		
		return ResultVo.ok();
	}

	/**
	 * 删除
	 * 
	 * @param id
	 * @return
	 * @author baolingyu
	 * @date 2018年8月28日-下午2:20:00
	 */
	@RequiresPermissions("product:manage:remove")
	@PostMapping("/remove")
	@ResponseBody
	public ResultVo remove(Long id) {
		if (id == null) {
			return ResultVo.error();
		}
		if (productService.remove(id) < 1) {
			return ResultVo.error();
		}
		return ResultVo.ok();
	}
	
	/**
	 * 跳转到选择商品页面，传参为商品id或者商品名称
	 * @param info
	 * @return
	 * @author baolingyu
	 * @date 2018年9月9日-上午10:57:56
	 */
	@RequiresPermissions("product:manage:manage")
	@GetMapping("/toSelectProduct")
	public String toSelectProduct(String info) {
		return prefix + "/select_product";
	}
	
	/**
	 * 列表
	 * 
	 * @return
	 * @author baolingyu
	 * @date 2018年8月28日-上午11:41:11
	 */
	@GetMapping("/allProduct")
	@ResponseBody
	@RequiresPermissions("product:manage:allProduct")
	public List<Product> allProduct(String idOrName) {
		return productService.list(idOrName);
	}
	
	/**
	 * 列表-分页
	 * 
	 * @return
	 * @author baolingyu
	 * @date 2018年8月28日-上午11:41:11
	 */
	@GetMapping("/allProductByPage")
	@ResponseBody
	@RequiresPermissions("product:manage:allProduct")
	public PageUtils<Product> allProduct(String idOrName, int limit, int offset, String upStartTime,String upEndTime) {
		return productService.listBaseProduct(offset, limit , idOrName,upStartTime,upEndTime);
	}
	
	/**
	 * 商品审核
	 * @param id
	 * @return
	 * @author baolingyu
	 * @date 2018年11月7日-上午11:22:50
	 */
	@PostMapping("/audit")
	@ResponseBody
	@RequiresPermissions("product:manage:audit")
	public ResultVo audit(Long id){
		pCentreService.btnUpdate(id, "audit");
		return ResultVo.ok();
	}
	
	/**
	 * 批量审核
	 * @param ids
	 * @return
	 * @author baolingyu
	 * @date 2018年11月19日-下午3:30:36
	 */
	@PostMapping("/batchAudit")
	@ResponseBody
	@RequiresPermissions("product:manage:audit")
	public ResultVo batchAudit(@RequestParam("ids[]") Long[] ids){
		if (ids.length < 1) {
            return ResultVo.error();
        }
		pCentreService.batchAudit(Arrays.asList(ids));
		return ResultVo.ok();
	}
	
	/**
	 * 批量更新销售数量
	 * @param ids
	 * @return
	 */
	@PostMapping("/batchUpdateSales")
	@ResponseBody
	public ResultVo batchUpdateSales(@RequestParam("ids[]") Long[] ids, @RequestParam("sales")int sales){
		if (ids.length < 1) {
            return ResultVo.error();
        }
		pCentreService.batchUpdateSales(Arrays.asList(ids),sales);
		return ResultVo.ok();
	}
	
	
	 /**
     * 导出
     * @param vo
     * @param idOrName
     * @param response
     */
	@RequiresPermissions("product:manage:exportProduct")
    @GetMapping("/exportProduct")
	public void exportProduct(Product vo, HttpServletResponse response) {
		List<List<Object>> resultData = new ArrayList<>();
		String[] head = { "序号", "ID","排序", "商品名称","分类","供应商名称","单位","商品属性", 
				"上架时间", "下架时间","开售时间", "停售时间","建议零售价","现价","市场价","成本价","佣金","销量",
				"库存","状态"};
		resultData.add(0, Arrays.asList(head));

		List<ProductVo>   list = productService.getExprotProductlist(vo);
		  int flag = 1;
		if (CollectionUtils.isNotEmpty(list)) {
			for (ProductVo obj : list) {
				if (obj == null) {
					continue;
				}
				String attr = "";
				String status ="";
				if (obj.getStatus() == 0) {
					status = "上架";
                }
                if (obj.getStatus() == 1) {
                	status = "下架";
                }
                if (obj.getStatus() == 2) {
                	status = "定时上架";
                }
//				 if(obj.getIszhicai()!=0) {
//					 attr = attr.concat("[直采]");
//			      }
		        if(obj.getIsmao()!=0) {
		        	attr= attr.concat("[特卖]");
		        }
//		        if(obj.getIsfanchang()!=0) {
//		        	attr= attr.concat("[返场]");
//		        }
//		        if(obj.getIszhutihuakuang()!=0) {
//		        	attr= attr.concat("[主题画框]");
//		        }
		        if(obj.getIsnew()!=0) {
		        	attr=attr.concat("[新品]");
		        }
//		        if(obj.getIsbig()!=0) {
//		        	attr=attr.concat("[大件]");
//		        }
//		        if(obj.getIslimited()!=0) {
//		        	attr=attr.concat("[限量]");
//		        }
//		        if(obj.getIsmiaosha()!=0) {
//		        	attr= attr.concat("[秒杀]");
//		        }
//		        if(obj.getIsvip()!=0) {
//		        	attr= attr.concat("[vip]");
//		        }
		        if(obj.getIshot()!=0) {
		        	attr=attr.concat("[爆款]");
		        }
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				List<Object> row = new ArrayList<>();
				row.add(flag);
				row.add(obj.getId());
				row.add(obj.getDisplayorder());
				row.add(obj.getTitle());
				row.add(obj.getCategoryName());
				row.add(obj.getSupplyNm());
				row.add(obj.getUnit());
				row.add(attr);
				row.add(obj.getUpStartTime()==null?"":sdf.format(obj.getUpStartTime()));
				row.add(obj.getUpEndTime()==null?"":sdf.format(obj.getUpEndTime()));
				row.add(obj.getTimestart() == null ? "" : sdf.format(obj.getTimestart()));
				row.add(obj.getTimeend()== null ? "" : sdf.format(obj.getTimeend()));
				row.add(obj.getSuggestsaleprice());
				row.add(obj.getMarketprice());
				row.add(obj.getProductprice());
				row.add(obj.getCostprice());
				row.add(obj.getHeadcommission());
				row.add(obj.getSalesreal());
				row.add(obj.getTotal());
				row.add(status);
				resultData.add(row);
				flag++;
			}
		}
		String fileName = "平台商品_" + DateUtils.format(new Date(), "yyyyMMddHHmmss");
		try {
			ExcelHelper.exportExcel(response, fileName, "平台商品", resultData);
		} catch (IOException e) {
			logger.info("export achieve count error:{}", e.getMessage());
		}
	}
	        		
	
	/**
	 * 复制
	 * 
	 * @param id
	 * @return
	 * @author baolingyu
	 * @date 2018年8月28日-下午2:20:00
	 */
	@RequiresPermissions("product:manage:add")
	@PostMapping("/copy")
	@ResponseBody
	public ResultVo copy(Long id) {
		if (id == null) {
			return ResultVo.error();
		}
		if (productService.copyProduct(id) < 1) {
			return ResultVo.error();
		}
		return ResultVo.ok();
	}

	/**
	 * 批量复制
	 *
	 * @param ids
	 * @return
	 * @author baolingyu
	 * @date 2018年8月28日-下午2:20:00
	 */
	@RequiresPermissions("product:manage:add")
	@PostMapping("/copyBatch")
	@ResponseBody
	public ResultVo copyBatch(@RequestParam("ids[]") Long[] ids) {
		if (ids == null || ids.length<=0) {
			return ResultVo.error();
		}
		for(Long id:ids){
			productService.copyProduct(id);
		}
		return ResultVo.ok();
	}
}

